package com.shirotest.utility;

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
/**
 * JSON工具类
 */
public class JsonUtility {
	private static ObjectMapper mapper = new ObjectMapper();
	
	/**
	 * 获取一个空的可编辑的ObjectNode（JsonNode的子类）
	 * @return
	 */
	public static ObjectNode crateObjectNode() {
		return mapper.createObjectNode();
	}
	
	/**
	 * 将JSON格式的字符串转成JsonNode，允许斜杠等字符串
	 */
	public static JsonNode strToJsonNode(String json){
		try{
		    return mapper.readTree(json);
		}catch(Exception e){
			return null;
		}
    }
	
	/**
	 * 实体类转JSON字符串
	 */
	public static String entityToJsonString(Object entity){
		try{
	        return mapper.writeValueAsString(entity);
		}catch(Exception e){
			return "";
		}
	}

    /**
     * 将JSON字符串转换为对象
     * @param <T>
     * @param json
     * @param dataType
     * @param genericityTypes
     * @return
     */
    public static <T> T jsonToObject(String json, Class<?> dataType, Class<?>... genericityTypes){
    	try {
    		return mapper.readValue(json,mapper.getTypeFactory().constructParametricType(dataType, genericityTypes));
    	}catch(Exception e) {
    		return null;
    	}
    }
    
    /**
     * JSON转换为list数组
     * @param <T>
     * @param json
     * @param dataType
     * @return
     */
    public static <T> List<T> jsonToList(String json,Class<?> dataType){
    	try {
    		return mapper.readValue(json,mapper.getTypeFactory().constructParametricType(List.class, dataType));
    	}catch(Exception e) {
    		return null;
    	}
    }
    
    /**
     * JSON转换为Map集合
     * @param <T>
     * @param json
     * @param dataType
     * @return
     */
    public static <T> T jsonToMap(String json,Class<?> keyType,Class<?> valueType){
    	try {
    		return mapper.readValue(json,mapper.getTypeFactory().constructParametricType(Map.class, keyType,valueType));
    	}catch(Exception e) {
    		return null;
    	}
    }


    /**
     * 将JSON字符串转换为对象
     */
    public static <T> T jsonToObject(String json, Class<T> dataType){
        try {
    		return mapper.readValue(json, dataType);
    	}catch(Exception e) {
    		return null;
    	}
    }
	
	/**
	 * 判断给定的JsonNode对象中key为fieldName对应的value值是否为空
	 */
	public static boolean isfieldNull(JsonNode jsonNode,String fieldName){
		if(jsonNode == null || fieldName == null 
				|| fieldName.trim().length() == 0 
				|| !jsonNode.hasNonNull(fieldName)){
			return true;
		}
		
		JsonNode child = jsonNode.get(fieldName);
		
		if(child == null){
			return true;
		}
		
		if(child instanceof TextNode){
			String fieldValue = jsonNode.get(fieldName).asText();
			if(fieldValue == null || fieldValue.trim().length() == 0){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 获取json中的字符串形式
	 */
	public static String getStringField(JsonNode jsonNode,String fieldName){
		if(jsonNode == null || fieldName == null 
				|| fieldName.trim().length() == 0 
				|| !jsonNode.hasNonNull(fieldName)){
			return "";
		}
		
		JsonNode child = jsonNode.get(fieldName);
		
		if(child instanceof TextNode){
			String fieldValue = jsonNode.get(fieldName).asText();
			if(fieldValue == null || fieldValue.trim().length() == 0){
				return "";
			}else{
				return fieldValue.trim();
			}
		}
		return child.toString();
	}
	
	/**
	 * 获取json中的字整形形式
	 */
	public static int getIntField(JsonNode jsonNode,String fieldName,int defaultValue){
		if(jsonNode == null || fieldName == null 
				|| fieldName.trim().length() == 0 
				|| !jsonNode.hasNonNull(fieldName)){
			return defaultValue;
		}
		
		JsonNode child = jsonNode.get(fieldName);
		
		if(child instanceof IntNode){
			return jsonNode.get(fieldName).asInt();
		}
		
		if(child instanceof TextNode){
			return jsonNode.get(fieldName).asInt();
		}
		return defaultValue;
	}
	
	/**
	 * 获取json中的字浮点型形式
	 */
	public static double getDoubleField(JsonNode jsonNode,String fieldName,double defaultValue){
		if(jsonNode == null || fieldName == null 
				|| fieldName.trim().length() == 0 
				|| !jsonNode.hasNonNull(fieldName)){
			return defaultValue;
		}
		
		JsonNode child = jsonNode.get(fieldName);
		
		if(child instanceof DoubleNode || child instanceof IntNode){
			return jsonNode.get(fieldName).asDouble();
		}
		
		if(child instanceof TextNode){
			return jsonNode.get(fieldName).asDouble();
		}
		return defaultValue;
	}
	
	/**
	 * 获取json中的布尔值形式
	 */
	public static boolean getBooleanField(JsonNode jsonNode,String fieldName,boolean defaultValue){
		if(jsonNode == null || fieldName == null 
				|| fieldName.trim().length() == 0 
				|| !jsonNode.hasNonNull(fieldName)){
			return defaultValue;
		}
		
		JsonNode child = jsonNode.get(fieldName);
		
		if(child instanceof BooleanNode){
			return jsonNode.get(fieldName).asBoolean();
		}
		
		if(child instanceof TextNode){
			return jsonNode.get(fieldName).asBoolean();
		}
		return defaultValue;
	}
	
	/**
	 * 获取json中的长整形形式
	 */
	public static long getLongField(JsonNode jsonNode,String fieldName,long defaultValue){
		if(jsonNode == null || fieldName == null 
				|| fieldName.trim().length() == 0 
				|| !jsonNode.hasNonNull(fieldName)){
			return defaultValue;
		}
		
		JsonNode child = jsonNode.get(fieldName);
		
		if(child instanceof LongNode){
			return jsonNode.get(fieldName).asLong();
		}
		
		if(child instanceof TextNode){
			return jsonNode.get(fieldName).asLong();
		}
		return defaultValue;
	}
	
	static {
		//是否自动关闭非分身的输入源，默认为true
		//mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE,true);
		
		//是否可以解析包含有注释样式的JSON字符串，例如/*或//注释符，默认为false
		mapper.configure(JsonParser.Feature.ALLOW_COMMENTS,true);
		
		//是否可以解析包含有#开头注释样式的JSON字符串，默认为false
		mapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS,true);
		
		//是否可以解析KEY没有双引号的JSON串，默认为false
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);
		
	    //是否解析KEY或者VALUE为单引号的JSON串，默认为false
	    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,true);
	    
	    //是否解析结束语控制符，如制表符\t 换行符\n，默认false
	    mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(),true);
	    
	    //是否可以解析反斜杠引用的所有字符
	    mapper.configure(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER.mappedFeature(),true);
	    
	    //允许数字以0开头
	    mapper.configure(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS.mappedFeature(),true);
	    
	    //转实体类时，如果JSON串中的字段比实体类多，则忽略多余的字段，默认为false
	    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	    
	    //序列化时属性值为null的不参与序列化
	    mapper.setSerializationInclusion(Include.NON_NULL);
	    
	    //忽略无法转换的对象
	    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
	}
}
